package com.and.yzy.frame.update;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.and.yzy.frame.util.AppUtils;
import com.and.yzy.frame.util.OkHttpUtils;
import com.and.yzy.frame.view.dialog.MaterialDialog;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 检测更新的工具类
 */
public class AppUpdateUtil {


    private String vistionUrl;
    private Context mContext;
    private FormBody formBody;

    public AppUpdateUtil(Activity context, String vistionUrl, FormBody formBody) {
        this.vistionUrl = vistionUrl;
        this.mContext = context;
        this.formBody = formBody;
    }


    public void checkUpdate(final UpdateCallBack callBack) {


        Request.Builder build = new Request.Builder()
                .url(vistionUrl);

        if (formBody != null) {
            build.post(formBody);
        }

        OkHttpUtils.getInstance().newCall(build.build()).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onError();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String result = response.body().string();

                try {
                    JSONObject jsonObject=new JSONObject(result);

                final Version version = JSON.parseObject(jsonObject.getString("data"), Version.class);

                Logger.v("url=="+version.getUri());

                if (Float.parseFloat(version.getCode()) > AppUtils.getVersionCode(mContext)) {
                    callBack.isUpdate(result);
                    Looper.prepare();
                    MaterialDialog materialDialog = new MaterialDialog(mContext);
                    materialDialog.setMDMessage(version.getMessage() + "\n版本号:" + version.getName())
                            .setMDTitle("更新提示")
                            .setMDConfirmBtnClick(new MaterialDialog.DialogBtnCallBack() {
                                @Override
                                public void dialogBtnOnClick() {
                                    Intent intent = new Intent(mContext, DownLoadService.class);
                                    intent.putExtra("url", version.getUri());
                                    mContext.startService(intent);
                                }
                            });

                    materialDialog.show();
                    Looper.loop();

                } else {

                    callBack.isNoUpdate();
                }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });


    }


}
